/**
 * 
 */
package com.munoor.dalai.server.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.Normalizer;

/**
 * @author Osho  2/04/2011
 * 
 */
public class Hash {

	public static HashHolder getMD5Hash(String plainText) {
		HashHolder hashHolder = new HashHolder();
		hashHolder.setSalt(getSalt());
		hashHolder.setHash(getMD5Hash(plainText, hashHolder.getSalt()));
		return hashHolder;
	}

	public static String getMD5Hash(String plainText, long salt) {
		MessageDigest md5 = null;
		boolean success = true;
		// init the digest algorithm and random salt generator
		try {
			md5 = MessageDigest.getInstance("md5");
		} catch (NoSuchAlgorithmException e) {
			success = false;
		} // should never happen

		String value = "" + salt + plainText;

		// normalize to NFC form
		value = Normalizer.normalize(value, Normalizer.Form.NFC);

		byte[] digest = null;

		try {
			digest = value.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			success = false;
		} // should never happen

		// hash iterations
		for (int i = 0; i < 1981; i++) {
			digest = md5.digest(digest);
		}

		String strDigest = new String(Encoder.encode(digest));
		//String strDigest = new String(Encoder.hexEncode(digest));
		
		if (success && (strDigest.length()> 0)){
			return strDigest;
		}else{
			return "";
		}
	}

	private static long getSalt() {
		SecureRandom random = null;
		try {
			random = SecureRandom.getInstance("SHA1PRNG");
		} catch (NoSuchAlgorithmException e) {
		} // should never happen
		return (random.nextLong()); // 8 byte salt
	}

}
